package me.illtamer.rpc.register;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.extern.slf4j.Slf4j;
import me.illtamer.rpc.enumeration.RpcError;
import me.illtamer.rpc.exception.RpcException;
import me.illtamer.rpc.loadbalancer.LoadBalancer;
import me.illtamer.rpc.loadbalancer.RandomLoadBalancer;
import me.illtamer.rpc.util.NacosUtil;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * 服务发现
 * */
@Slf4j
public class NacosServiceDiscovery implements ServiceDiscovery {

    private final LoadBalancer loadBalancer;

    public NacosServiceDiscovery(LoadBalancer loadBalancer) {
        if (loadBalancer != null)
            this.loadBalancer = loadBalancer;
        else
            this.loadBalancer = new RandomLoadBalancer();
    }

    /**
     * 根据服务名从注册中心获取道一个服务提供者的地址
     * */
    @Override
    public InetSocketAddress lookupService(String name) {
        try {
            List<Instance> instances = NacosUtil.getAllInstance(name);
            if (instances.size() == 0) {
                log.error("找不到对应服务 {}", name);
                throw new RpcException(RpcError.SERVICE_NOT_FOUND);
            }
            Instance instance = loadBalancer.select(instances);
            return new InetSocketAddress(instance.getIp(), instance.getPort());
        } catch (NacosException e) {
            log.error("获取服务时有错误发生", e);
        }
        return null;
    }

}
